/*
 * @Author: 吴世扬 18368095041@163.com
 * @Date: 2024-05-08 15:55:05
 * @LastEditors: 吴世扬 18368095041@163.com
 * @LastEditTime: 2025-05-23 15:06:16
 * @FilePath: /vue3-admin/src/utils/array.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
// export interface TreeData<T> {
//     children?: T[];
// }
// export type TreeDataWithParent<T extends TreeData<T>> = T & { parent?: T };
// export const treeToArray = <T extends TreeData<T>>(
//     tree: T[],
//     parent?: TreeDataWithParent<T>
// ): TreeDataWithParent<T>[] => {
//     let res: TreeDataWithParent<T>[] = [];
//     for (const item of tree) {
//         const { children, ...rest } = item;
//         const newItem = { children, ...rest, parent } as TreeDataWithParent<T>;
//         res.push(newItem);
//         if (children && children.length > 0) {
//             res = [...res, ...treeToArray(children, newItem)];
//         }
//     }
//     return res;
// };

// export function arrayToTree<T extends TreeData<T>>(
//     items: TreeDataWithParent<T>[]
// ): TreeData<T>[] {
//     // 用于构建树的辅助函数
//     function buildTree(parent?: T): T[] {
//         return items
//             .filter((item) => item.parent === parent) // 查找所有子节点
//             .map((item) => {
//                 const children = buildTree(item);
//                 return {
//                     ...item,
//                     children: children.length > 0 ? children : undefined, // 递归地构建子树
//                     parent: undefined // 在树中不需要父节点引用
//                 };
//             });
//         // .filter((item) => item.children.length > 0); // 过滤掉没有子节点且不是根节点的元素（可选）
//     }

//     // 从没有父节点的元素开始构建树
//     return buildTree();
// }

export type TreeData<T> = T & {
    children?: TreeData<T>[];
};

export type ListDataWithParent<T> = T & { parentId?: string | number };

export const treeToArray = <T>(
    key = 'id' as keyof T,
    tree: TreeData<T>[],
    parentId?: string | number
): ListDataWithParent<T>[] => {
    let res: ListDataWithParent<T>[] = [];
    for (const item of tree) {
        const newItem = { ...item, parentId: parentId };
        res.push(newItem);
        if (item.children && item.children.length > 0) {
            res = [
                ...res,
                ...treeToArray(
                    key,
                    item.children,
                    Reflect.get(item, key) as string | undefined
                )
            ];
        }
    }
    return res;
};

export function arrayToTree<T>(
    key = 'id' as keyof T,
    items: ListDataWithParent<T>[]
): TreeData<T>[] {
    const nodeMap: Record<string | number, TreeData<T>> = {}; // 哈希表存储节点
    const roots: TreeData<T>[] = [];

    // 初始化所有节点（包含children字段）
    items.forEach((item) => {
        nodeMap[item[key] as string | number] = {
            ...item,
            children: undefined
        };
    });

    // 建立父子关系
    items.forEach((item) => {
        const node = nodeMap[item[key] as string | number];
        if (item.parentId && Reflect.has(nodeMap, item.parentId)) {
            const parent = Reflect.get(nodeMap, item.parentId);
            if (parent.children) {
                parent.children.push(node); // 绑定子节点
            } else {
                parent.children = [node];
            }
        } else if (!item.parentId) {
            roots.push(node); // 无父节点则为根节点
        }
    });

    return roots;
}
